<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>

        <template #right>
          <el-button
            v-permission="'excel_import'"
            type="warning"
            size="small"
            @click="$router.push('/import?type=user')"
          >excel导入</el-button>
          <el-button
            v-permission="'excel_export'"
            type="danger"
            size="small"
            @click="exportExcel"
          >excel导出</el-button>
          <el-button
            v-permission="'p-em-add'"
            type="primary"
            size="small"
            @click="showDialogFn"
          >新增员工</el-button>
        </template>
      </page-tools>

      <el-card v-loading="isLoading" style="margin-top: 10px">
        <el-table border :data="employeeList">
          <el-table-column label="序号" type="index" width="80px" :index="indexMethod" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像" prop="username">
            <template #default="{row}">
              <img v-imgerror="defaultImg" class="staff" :src="row.staffPhoto||nullImage">
            </template>
          </el-table-column>
          <el-table-column label="手机号" prop="mobile" />
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment" :formatter="formateData" />
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry">
            <template #default="{row}">
              {{ formatTime(row.timeOfEntry) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="280">
            <template #default="{row}">
              <el-button
                v-permission="'p-em-look'"
                type="text"
                size="small"
                @click="$router.push(`/employees/detail/${row.id}`)"
              >查看</el-button>
              <el-button
                v-permission="'assign_role'"
                type="text"
                size="small"
                @click="assignRoleClick(row.id)"
              >分配角色</el-button>
              <el-button
                v-permission="'emp_delete'"
                type="text"
                size="small"
                @click="delEmployeesList(row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <div style="height: 60px; margin-top: 10px">
          <el-pagination
            :current-page="page"
            :page-size="size"
            :page-sizes="[10, 20, 30, 40]"
            layout="total,sizes,prev, pager, next,jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
      <add-employees :show-dialog.sync="showDialog" />
      <assignRole :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
    </div>
  </div>
</template>

<script>
import { getEmployeesListAPI, delEmployeesListAPI } from '@/api/employees'
import EmpLoyess from '@/constant/employees'
import dayjs from 'dayjs'
import addEmployees from './components/add-employees.vue'
import assignRole from './components/assign-role.vue'
import avatar from '@/assets/common/bigUserHeader.png'
// 使用mixins的方式  1.先导入mixins所在的文件 2.把mixins混入当前组件中(mixins: [index])
import permission from '@/mixins/permission'
export default {
  name: 'Employees',
  components: { addEmployees, assignRole },
  mixins: [permission],
  data() {
    return {
      page: 1,
      size: 10,
      employeeList: [],
      total: 0,
      isLoading: false,
      showDialog: false,
      defaultImg: avatar,
      showRoleDialog: false,
      userId: '',
      nullImage: 'http://heimamianjing-1315206099.cos.ap-beijing.myqcloud.com/1669080961265%E8%87%AD%E5%AE%9D.jpg'
    }
  },
  created() {
    this.getEmployeesList()
  },
  methods: {
    assignRoleClick(id) {
      this.showRoleDialog = true
      this.userId = id
    },
    // 导出
    async exportExcel() {
      const headersArr = ['姓名',
        '手机号',
        '入职日期',
        '聘用形式',
        '转正日期',
        '工号',
        '部门']
      const headersRelations = {
        姓名: 'username',
        手机号: 'mobile',
        入职日期: 'timeOfEntry',
        聘用形式: 'formOfEmployment',
        转正日期: 'correctionTime',
        工号: 'workNumber',
        部门: 'departmentName'
      }
      const { data: { rows }} = await getEmployeesListAPI(1, this.total)
      const data = this.formateData2Array(headersArr, headersRelations, rows)
      const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
      const merges = ['A1:A2', 'B1:F1', 'G1:G2']
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          // excel表头
          header: headersArr,
          // excel数据(导出的数据必须是二维数组)
          data: data,
          // 导出文件的文件名(非必填)
          filename: '员工信息',
          // 单元格宽度是否自适应(非必填)
          autoWidth: true,
          // 文件后缀名(非必填)
          bookType: 'xlsx',
          multiHeader,
          merges
        })
      })
    },
    formateData2Array(headersArr, headersRelations, rows) {
      const arr = []
      rows.forEach(item => {
        const tempArray = []
        headersArr.forEach(key => {
          const englishKey = headersRelations[key]
          let value = item[englishKey]
          // 处理聘用形式
          if (englishKey === 'formOfEmployment') {
            const hireObj = EmpLoyess.hireType.find(item => item.id === Number(value))
            value = hireObj ? hireObj.value : '未知'
          }
          // 处理时间格式化
          if (['timeOfEntry', 'correctionTime'].includes(englishKey)) {
            value = value ? this.formatTime(value) : ''
          }
          // 最后赋值
          /* tempArray.push(item[englishKey]) */
          tempArray.push(value)
        })
        arr.push(tempArray)
      })
      return arr
    },
    showDialogFn() {
      this.showDialog = true
    },
    delEmployeesList(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
      }).then(async() => {
        await delEmployeesListAPI(id)
        this.$message.success('删除成功！')
        if (this.employeeList.length === 1 && this.page > 1) {
          this.page--
        }
        this.getEmployeesList()
      }).catch(() => {
        this.$message.error('删除失败！')
      })
    },
    formatTime(time) {
      return dayjs(time).format('YYYY-MM-DD')
    },
    formateData(row, column, cellValue, index) {
      const hireObj = EmpLoyess.hireType.find(item => item.id === Number(cellValue))
      return hireObj ? hireObj.value : '未知'
    },
    async getEmployeesList() {
      this.isLoading = true
      const { data } = await getEmployeesListAPI(this.page, this.size)
      this.employeeList = data.rows
      this.total = data.total
      this.isLoading = false
    },
    /**
     * 页容量改变
     */
    handleSizeChange(val) {
      this.size = val
      this.getEmployeesList()
    },
    /**
     * 页码改变
     */
    handleCurrentChange(val) {
      this.page = val
      this.getEmployeesList()
    },
    indexMethod(index) {
      return (this.page - 1) * this.size + index + 1
      // return index + 1
    }
  }
}
</script>

<style lang="scss" scoped>
.employees-container {
    .staff {
      width: 70px;
      height: 70px;
      border-radius: 50%;
    }
  }
</style>
